//
//  WeclomeController.m
//  ZZmetro
//
//  Created by 一介布衣 on 2020/6/5.
//  Copyright © 2020 一介布衣. All rights reserved.
//

#import "WelcomeController.h"
#import <FLAnimatedImage/FLAnimatedImage.h>
#import "Session.h"
#import "LaunchHandler.h"

@interface WelcomeController () {
    int countDown;
}

@property (strong, nonatomic) UIButton *skipBtn;

@property (strong, nonatomic) FLAnimatedImageView *imageView;

@property (nonatomic,strong) dispatch_source_t timer;

@end

@implementation WelcomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    countDown = 1;
    
    [self initViews];
    [self initTimer];
    //[self autoLogin];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(self.timer) {
        dispatch_resume(self.timer);
    }
}

- (void)initViews{
    FLAnimatedImageView* imageView = [[FLAnimatedImageView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:imageView];
    _imageView = imageView;
    
    UIImage* image = [UIImage imageNamed:@"bg_welcome.jpeg"];
    //UIImage* image = [UIImage imageNamed:@"login_logo.jpeg"];
    _imageView.image = image;
    
    /*
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = FONT(15);
    button.frame = CGRectMake(SCREEN_WIDTH-48, isIphoneX?44:20, 32, 32);
    button.backgroundColor = HEXCOLOR(0xEBEBEB);
    button.layer.cornerRadius = 16.0;
    [button setTitleColor:COLOR_VIEW_3 forState:UIControlStateNormal];
    [button addTarget:self action:@selector(skipAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    _skipBtn = button;*/
}

/// 初始化定时器
- (void)initTimer{
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        [Queue async:^{
            if(countDown > 0){
                [self.skipBtn setTitle:[NSString stringWithFormat:@"%d",countDown] forState:UIControlStateNormal];
                
                countDown --;
                
            }else{
                [self timerDone];
            }
        }];
    });
    _timer = timer;
}

/// 获取登录信息
- (void)autoLogin{
    //todo
}

#pragma mark -- actions

- (void)skipAction:(id)sender {
    [self timerDone];
}

#pragma mark -- launch

- (void)timerDone{
    [self cancelTimer];
    
    //如果没登录，进入登录，否则进入主页
    if (Session.isLogin) {
        [LaunchHandler toHomeController];
    } else {
        [LaunchHandler toLoginController];
    }
}

- (void)cancelTimer{
    if(self.timer)
        dispatch_source_cancel(self.timer);
    self.timer = NULL;
}

- (void)dealloc{
    [self cancelTimer];
}

@end
